package per.jdz.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import per.jdz.annotation.Aop;
import per.jdz.core.ProxyFactory;

@Component
public class PointBeanPostProcess implements BeanPostProcessor {

    // 需要路径切入点的bean
    Map<String, Object> jointPointPathMap;

    Map<Class, Object> jointPointAnnotationMap;

    public PointBeanPostProcess() {
        jointPointPathMap = new HashMap<>();
        jointPointAnnotationMap = new HashMap<>();
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        final Class<?> beanClass = bean.getClass();
        final String path = beanClass.getName();
        // 匹配
        for (String ks : jointPointPathMap.keySet()) {
            if (path.startsWith(ks)) {
                return ProxyFactory.tryBuild(bean, jointPointPathMap.get(ks));
            }
        }
        for (Object aopoObject : jointPointAnnotationMap.values()) {
            return ProxyFactory.tryBuild(bean, aopoObject);
        }
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        final Class<?> beanClass = bean.getClass();
        final Aop aop = beanClass.getAnnotation(Aop.class);
        if (aop != null) {
            final String jointPath = aop.jointPath();
            // 两个中只能生效一个
            if (!jointPath.equals("")) {
                jointPointPathMap.put(jointPath, bean);
            } else {
                jointPointAnnotationMap.put(aop.joinAnnotationClass(), bean);
            }
        }
        return bean;
    }

}
